# -*- coding: utf-8 -*-
from flask import json
import redis
from scrapy_redis.spiders import RedisSpider
from scrapy import Request, FormRequest
from spider.ops import Ops
from facility.time_fn import timestamp2string
import subprocess


class FenghuiSpider(RedisSpider):
    name = 'fenghui'
    redis_key = 'fenghui:start_urls'
    v8host = 'http://localhost:5000/'

    con = redis.Redis(host='localhost', port=6379, db=0)
    con.lpush(redis_key, v8host)

    def parse(self, response):
        total = 9999
        # yield Request(url='', dont_filter=True, callback=self.parse_item)
        yield FormRequest(url='https://www.fhjr.com/financing/sbtz/index.htm',
                          formdata={"currentPage": "1",
                                    "pageSize": "{}".format(total),
                                    "yearRate": "",
                                    "progress": "",
                                    "status": "",
                                    "productId": "",
                                    },
                          dont_filter=True, callback=self.parse_item)

        # yield FormRequest(
        #    url = self.v8host,
        #    formdata = {"to" : "https://www.klmygsjr.com/BID/Debt/DebtList"},
        #    dont_filter=True,
        #    callback = self.parse_item
        # )

    def parse_item(self, response):
        q = Ops(response)
        for i in q.get_json()['bidList']:
            idx = i['F02']
            yield FormRequest(
                url='https://www.fhjr.com/financing/sbtz/bdxqData.htm',
                formdata={"type": "bdxq",
                          "id": str(idx),
                          "pageSize": "10",
                          "currentPage": "1"},

                dont_filter=True,
                callback=self.parse_detail
            )

    def parse_detail(self, response):
        trans = {
            "DBDX": "等本等息",
            "MYFX": "每月付息,到期还本"
        }
        q = Ops(response)
        data = q.get_json()["bdxqData"]['bdxq']

        name = data["F03"]
        amount = data["F05"]
        rate = str(data["F06"] * 100) + "%"
        cycle = data["F09"]

        if data["F10"] in trans:
            way = trans[data["F10"]]
        else:
            way = "等本等息"

        start = timestamp2string(data['F22'])

        res = name + " " + str(amount) + " " + rate + " " + str(start) + " " + str(cycle) + " " + way

        subprocess.call("echo  {} >>丰汇.txt".format(res.replace('￥', '').replace('元', '')), shell=True)
